Uec3.QuotationSearchWindow = Ext.extend(Ext.Window, {
	initPanel : function(initParams) {
		
		// 来源下拉框
		this.sourceType_store = getDictionaryStore(RES_PATH, {
					group : 'part_source'
				});
		this.source_cmb = getDictionaryComboBox(this.sourceType_store, 'local',
				'part_source', '来源', 'source', 90);
				
		this.sourceType_store.load();
		
		this.source_cmb1 = Uec3.App.dictionary.getCombo("part_source", {showWhole:true, width:80, hiddenName : 'source'});
		
		this.quotation_form_item = this.createQuotationFormItem();
		this.quotation_item_store = this.createQuotationItemStore();
		this.quotation_item_grid = this.createQuotationItemGrid();
//		Ext.util.Observable.capture(this.quotation_item_grid, function(e) {
////			console.debug(e);
//		});
		
		this.quotation_panel = this.createQuotationPanel();
		
		this.add(this.quotation_panel);
		
		//窗口出来之后触发
		this.on('show',function() {
			Ext.Ajax.request({
				url : RES_PATH + '/partner/getOtherPartnerByCompId.do',
				params : {'id' : this.compId},
				success : function(res) {
					this.discount = Ext.decode(res.responseText).discount;
					this.quotation_item_store.load();
				}.createDelegate(this)
			});
		
			Ext.util.Observable.capture(this.quotation_item_store, function(e) {
				if (e == 'load') {
					this.checkIsRecordSelected( );
				}
			}.createDelegate(this));
			
		}, this, {single : true});
		
//		this.doLayout();
		this.show();
//		this.creator.app.getDesktop().addAutoRun(this.getId());
		
	},
	checkIsRecordSelected : function() {
		var recs = this.quotation_item_store.getRange();
//				alert(recs.length);
		for (var i = 0; i < recs.length; i++) {
			var rec = recs[i];
			var purRecs = this.purStore.getRange();
			for(var j = 0; j < purRecs.length; j++) {
				var purRec = purRecs[j];
				if (rec.data.code + '&' + rec.data.source + '' == purRec.data.code + '&' + purRec.data.source + '') {
					rec.set('is_selected', "是");
					rec.set('inputQty', purRec.data.orderQuantity);
				}
			}
		}
	},
	// private
	moduleActionHtml : function(moduleId, action, value) {
		
		var record = this.quotation_item_store.getById(value);
		var disp1 = '';
		var disp2 = 'none';
		var inputQty = record.get('inputQty') + '';
		if(record.get('is_selected') && (record.get('is_selected')+'').trim() == '是' && inputQty.trim() != '') {
			disp1 = 'none';
			disp2 = '';
		}
		
		var quotationSearchWindow = "Uec3.App.getDesktop().getWindow('quotationSearchWindow')";
		
		var add = "<a style='font-size:12px;display:" + disp1 + "' href=javascript:" + quotationSearchWindow + "." 
			+ action.func1 + "(" + value + "); >" + action.desc1 + "</a>";
			
		var remove = "<a style='font-size:12px;display:" + disp2 + "' href=javascript:" + quotationSearchWindow + "." 
			+ action.func2 + "(" + value + "); >" + action.desc2 + "</a>";
			
		return add + remove;
	},
	moduleActionRenderer : function(actions) {
		var ref = this;
		if (Ext.isArray(actions)) {
			return function(value, cellmeta, record, rowIndex, columnIndex, store) {
				var html = "";
				for (var i = 0; i < actions.length; i++) {
					var v = value;
					if (actions[i].reader) {
						v = actions[i].reader(value, cellmeta, record, rowIndex, columnIndex, store);
					}
					html += ref.moduleActionHtml(ref.creator.id, actions[i], v) + "&nbsp;&nbsp;";
				}
				return html;
			};
		} else {
			return function(value, cellmeta, record, rowIndex, columnIndex, store) {
				var v = value;
				if (actions.reader) {
					v = actions.reader(value, cellmeta, record, rowIndex, columnIndex, store);
				}
//				alert(record);
				return ref.moduleActionHtml(ref.creator.id, actions, v);
			};
		}
	},
	createQuotationFormItem : function() {
		return {

			style : 'padding:0px;fontSize:13px;',
			layout : 'hbox',
			width : 1010,
			heigth : 80,
			items : [

					{
						xtype : 'label',
						text : '编码:',
						style : {
							marginLeft : '1px',
							width : '50px'
						}
					}, {
						xtype : 'textfield',
						name : 'code',
						// id : 'code',
						style : {
							width : '70px'
						}
					}, {
						xtype : 'label',
						text : '名称:',
						style : {
							marginLeft : '20px',
							width : '65px'
						}
					}, {
						xtype : 'textfield',
						name : 'name',
						// id : 'name',
						style : {
							width : '70px'
						}
					}, {
						xtype : 'label',
						text : '车型:',
						style : {
							marginLeft : '20px',
							width : '65px'
						}
					}, {
						xtype : 'textfield',
						name : 'carModel',
						// id : 'carModel',
						style : {
							width : '70px'
						}
					}, {
						xtype : 'label',
						text : '来源:',
						style : {
							marginLeft : '20px',
							width : '65px'
						}
					}, this.source_cmb1, {
						xtype : 'label',
						text : '品牌:',
						style : {
							marginLeft : '20px',
							width : '65px'
						}
					}, {
						xtype : 'textfield',
						name : 'brand',
						// id : 'brand',
						style : {
							width : '70px'
						}
					}, {
						xtype : 'label',
						text : '产地:',
						style : {
							marginLeft : '20px',
							width : '65px'
						}
					}, {
						xtype : 'textfield',
						name : 'origin',
						// id : 'origin',
						style : {
							width : '70px'
						}
					}, {
						xtype : 'button',
						text : '查    找',
						width : 60,
						style : {
							marginLeft : '30px'
						},
						listeners : {
							click : function() {

//								if (!this.validateSellerIsNotNull()) {
//									return;
//								}

								var params = this.quotation_panel.getForm().getValues();
								params = castNoSelToNULL(params);
								params.companyId = this.compId;
								
								params = Ext.util.JSON.encode(params);
								
								this.quotation_item_store.baseParams = {'queryParam' : params};

								this.quotation_item_store.load();
								
							}.createDelegate(this)
						}

					}
				]
		};

	},
	createQuotationItemStore : function() {

		// 报价单
		var quotation_item_record = Ext.data.Record.create([{
					name : 'id'
				}, {
					name : 'code'
				}, {
					name : 'name'
				}, {
					name : 'carModel'
				}, {
					name : 'companyId'
				}, {
					name : 'source'
				}, {
					name : 'measurementUnit'
				}, {
					name : 'brand'
				}, {
					name : 'origin'
				}, {
					name : 'retailPrice'
				}, {
					name : 'discount'
				}, {
					name : 'price'
				}, {
					name : 'exec'
				}, {
					name : 'partId'
				}, {
					name : 'level1Name'
				}, {
					name : 'level2Name'
				}, {
					name : 'level1Id'
				}, {
					name : 'partCategoryId'
				}, {
					name : 'durability'
				}, {
					name : 'inventoryIdBySeller'
				}, {
					name : 'inputQty'
				}]);

		var queryParam = Ext.util.JSON.encode({'companyId' : this.compId});		
		
		return new Ext.data.JsonStore({
			url : RES_PATH + "/quotation/searchCompanyQuotation.do",
			baseParams : {'queryParam' : queryParam},
			mode : "local",
			totalProperty : "totalProperty",
			root : "root",
			idProperty : "id",
			pruneModifiedRecords : true,
			fields : quotation_item_record
		});
		
		
//		return new Ext.data.Store({
//
//			proxy : new Ext.data.HttpProxy({
//				url : RES_PATH + "/quotation/searchCompanyQuotation.do",
//				method : 'post'
//			}),
//			pruneModifiedRecords : true,
//			paramNames : {
//				start : "start",
//				limit : "limit"
//			},
//			baseParams : {
//				'queryParam' : queryParam
//			},
//			remoteSort : true,
//			reader : new Ext.data.JsonReader({
//				totalProperty : 'totalProperty',
//				root : 'root'
//			}, quotation_item_record)
//		});

	},
	createQuotationItemGrid : function() {

		// 定义报价单grid表头
		var quotation_item_colName = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),
				{
					header : '订购数量',
					dataIndex : 'inputQty',
					editor : new Ext.form.NumberField({
						regex : /([1-9][0-9]*(\.\d+)?)|(0\.\d+)/,
						regexText : '您只能够输入数字'
					})
				}, {
					header : '已选中',
					dataIndex : 'is_selected'
				}, {
					header : '操作',
					id : 'exec',
					dataIndex : 'id',
					renderer : this.moduleActionRenderer({
						func1 : 'checkOwnerPartProperty',
						desc1 : '订购',
						func2 : 'quotationClickToCancel',
						desc2 : '取消'
					})
				}, {
					header : '零件编码',
					dataIndex : 'code'
				}, {
					header : '零件名称',
					dataIndex : 'name'
				}, {
					header : '车型',
					dataIndex : 'carModel'
				}, {
					header : '来源',
					dataIndex : 'source',
					renderer : Ext.util.Format.comboRenderer(this.source_cmb)
				}, {
					header : '单位',
					dataIndex : 'measurementUnit'
				}, {
					header : '品牌',
					dataIndex : 'brand',
					sortable : true
				}, {
					header : '产地',
					dataIndex : 'origin',
					sortable : true
				}, {
					header : '媒体价',
					dataIndex : 'retailPrice'
				}, {
					header : '折扣',
					dataIndex : 'discount',
					renderer : function(value, cellmeta, record, rowIndex, columnIndex, store) {
						return this.discount + '%';
					}.createDelegate(this)
				}, {
					header : '折后价',
					dataIndex : 'price',
					renderer : function(value, cellmeta, record, rowIndex, columnIndex, store) {
						return Ext.util.Format.number((this.discount/100) * (record.get('retailPrice')), '0.00');
					}.createDelegate(this)
				}]);

//		function createAddQuotaBtn(value, metadata, record, rowIndex, colIndex,
//				store) {
//
//			return '<div style="font-size:12px;"><a id="' + QUO_BUY_REOCRD_ID + record.data.id
//					+ this.versionCode + '" href="#">订购</a></div>';
//		}

		var c = 0;
				
		// 创建grid，装载明细数据
		return new Ext.grid.EditorGridPanel({
//			id : 'quotation_item_grid_id' + this.versionCode,
			style : {padding : '2px'},
			height : 320,
			clicksToEdit : 1,
			store : this.quotation_item_store,
			iconCls : 'icon-grid',
			loadMask : {
				msg : '数据加载中...'
			},
			viewConfig : {
				forceFit : true
			},
			cm : quotation_item_colName,
			bbar : new Ext.PagingToolbar({
				pageSize : purOrSaleOrderPageSize,
				store : this.quotation_item_store,
				displayInfo : true,
				displayMsg : '第 {0} - {1} 条  共 {2} 条',
				emptyMsg : "没有记录"
			}),
			listeners : {
				'validateedit' : function(e) {
					if((e.value + '').trim() == '') {
						return false;
					}
				},
				'afteredit': function(e) {
					if(e.field == 'inputQty') {
						var inputQty = e.record.get('inputQty') + '';
						if(e.record.get('is_selected') && (e.record.get('is_selected')+'').trim() != '' && inputQty.trim() != null) {
							
							var records = this.purStore.getRange();
							for (var i = 0; i < records.length; i++) {
								var rec = records[i];
								if (rec.data.code + '&' + rec.data.source + '' == e.record.data.code + '&' + e.record.data.source + '') {
									rec.set('orderQuantity', inputQty);
									return ;
								}
							}
						}
					}
				}.createDelegate(this),
				'mouseout' : function() {
//					console.debug('mouseout');
					if(this.activeEditor) {
						c++;
						if(c == 2) {
							c = 0;
							this.stopEditing();
						}
					}
				}

			}
		});
	
	},
	createQuotationPanel : function() {
//				alert(this.quotation_item_store);
		// 报价面板
		return new Ext.FormPanel({
			frame : true,
			height : 180,
			items : [this.quotation_form_item,
					this.quotation_item_grid]
		});

	},
	validatePur : function(rcd) {
		var records = this.purStore.getRange();
		for (var i = 0; i < records.length; i++) {
			var rec = records[i];
			if (rec.data.code + '&' + rec.data.source + '' == rcd.data.code + '&' + rcd.data.source + '') {
				Ext.Msg.alert(PurChaseAlert.PROMOTE_ERROR, '对不起，该行记录您已经选择..');
				return false;
			}
		}
		
		if(!rcd.get('inputQty') || (rcd.get('inputQty')+'').trim() == '') {
			Ext.Msg.alert(PurChaseAlert.PROMOTE_ERROR, '对不起，您的订购数量不可以为空..');
			return false;
		}
		
		if((rcd.get('inputQty')+'').trim() == '0') {
			Ext.Msg.alert(PurChaseAlert.PROMOTE_ERROR, '对不起，您的订购数量不可以为0..');
			return false;
		}
		
		return true;
	},
	getPurRecord : function(_record) {
		var data = _record.data
		var purData = {};
//		purData.orderQuantity = 1;

		purData.name = data.name;
		purData.code = data.code;
		purData.source = data.source;
		purData.measurementUnit = data.measurementUnit;
		purData.brand = data.brand;
		purData.origin = data.origin;
		purData.retailPrice = data.retailPrice;
		purData.discount = this.discount;
		purData.price = Ext.util.Format.number((this.discount/100) * (data.retailPrice), '0.00');
		purData.level1Name = data.level1Name;
		purData.level2Name = data.level2Name;
		purData.level1Id = data.level1Id;
		purData.partId = data.partId;
		purData.partCategoryId = data.partCategoryId;
		purData.durability = data.durability;
		purData.inventoryIdBySeller = data.inventoryId;
		purData.carModel = data.carModel;
		purData.orderQuantity = data.inputQty;
		var record = new this.purRecord(purData);
		
		return record;
	},
	checkOwnerPartProperty : function(id) {
		var record = this.quotation_item_store.getById(id);
		
		if (!this.validatePur(record)) {
			return;
		}
		
		Ext.Ajax.request({
			url : RES_PATH + '/part/query_partProperty!searchPartPropertyBySouAndCode.do',
			params : {'json' : Ext.encode(record.data)},
			success : function(res) {
				var obj = Ext.decode(res.responseText);
				if( !obj.partProperty) {
					
					Ext.Msg.confirm("提示", '您的库存里还没有该零件，所以暂不能选择，您愿意现在就添加吗？', function(btnId) {
						if(btnId == 'no') {
							return;
						} else {
							var desktop = Uec3.App.getDesktop();
							var data = copyObj(record.data);
							delete data.id;
							desktop.launchWindowByParam('partPropertyOperation', {'type' : 'add', 'data' : data, 'fn' : this.quotationClickToAdd.createDelegate(this, [id]) });
							
						}
					}.createDelegate(this));
					
				} else {
					this.quotationClickToAdd(id);
				}
			}.createDelegate(this)
		});
		
	},
	quotationClickToAdd : function(id) {
		
		var record = this.quotation_item_store.getById(id);

		record.set('is_selected', '是');

		var purRecord = this.getPurRecord(record);

		var index = this.purStore.getCount();
	
		this.purStore.insert(index, purRecord);
		
		var td = this.quotation_item_grid.getView().getCell(this.quotation_item_store.indexOf(record), this.quotation_item_grid.getColumnModel().getIndexById('exec'));
		var addA = Ext.get(td).select('a').elements[0];
		addA.style.display = 'none';

		var removeA = Ext.get(td).select('a').elements[1];
		removeA.style.display = '';
	},
	quotationClickToCancel : function(id) {
		var record = this.quotation_item_store.getById(id);
		record.set('is_selected', '');
		record.set('inputQty', '');

		var records = this.purStore.getRange();
		for (var i = 0; i < records.length; i++) {
			var rec = records[i];
			if (rec.data.code + '&' + rec.data.source + '' == record.data.code + '&' + record.data.source + '') {

				this.purStore.remove(rec);
				return ;
			}
		}
		
		var removeA = Ext.get(td).select('a').elements[1];
		removeA.style.display = 'none';

		var addA = Ext.get(td).select('a').elements[0];
		addA.style.display = '';
	}
});

Uec3.QuotationSearchWindowCreator = Ext.extend(Ext.app.Module, {
	id : 'quotationSearchWindowCreator',
	type : 'common/notepad',
	createWindow : function(initParams) {
		var desktop = this.app.getDesktop();
		var main_win = desktop.getWindow('quotationSearchWindow');
		if( !main_win ) {
			main_win = desktop.createWindowNoTask({
				id : 'quotationSearchWindow',
				modal : true,
				title : '[ESC退出] 搜索' + initParams.compName + '报价',
				width : 980,
				height : 380,
				iconCls : 'acc-icon',
				animCollapse : false,
	            constrainHeader : true,
	            maximizable : false,
	            minimizable : false,
				taskbuttonTooltip : '搜索' + initParams.compName + '报价',
				layout : "fit"
			}, Uec3.QuotationSearchWindow);
		}
		main_win.purGrid = initParams.purGrid ;
		main_win.purStore = main_win.purGrid.getStore();
		main_win.purRecord = initParams.purRecord;
		main_win.compId = initParams.compId;
		
		main_win.creator = this;
		main_win.versionCode = ++(PurchaseCount.count);
		main_win.initPanel(initParams);
	}
});